package cn.house.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.house.common.PublicResultJosn;
import cn.house.dto.LoginUser;
import cn.house.entity.UserInfo;
import cn.house.service.UserInfoService;
import cn.house.service.UserService;
import cn.house.utils.UserUtil;

@RestController
@RequestMapping("/auth")
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private UserInfoService userInfoService;

	@PostMapping("/currentUser")
	public UserDetails currentLoginUser(@AuthenticationPrincipal UserDetails user) {
		return user;
	}

	@PostMapping("/refresh")
	public PublicResultJosn refresh() {
		LoginUser loginUser = UserUtil.getCurrentUser();
		//类似于重新登录,刷新cookie
		loginUser = userService.selectByUsername(loginUser.getUsername());
		UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null,
				loginUser.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);
		return new PublicResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "");
	}

	/**
	 * 注册
	 */
	@PostMapping("/register")
	public PublicResultJosn register(@RequestBody UserInfo userInfo) {
		Wrapper<UserInfo> queryWrapper = new QueryWrapper<>();
		UserInfo one = userInfoService.getOne(queryWrapper, true);
		if (null != one) {
			throw new IllegalArgumentException("用户名已存在");
		}
		userInfoService.save(userInfo);
		return new PublicResultJosn(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "");
	}

}
